package com.rui.shangXueTang.linked;

/**
 * @author : [锐神NO.3]
 * @version : [v1.0]
 * @className : OddLinkedList
 * @createTime : [2022/2/13 20:50]
 * @description : [单链表]
 */

public class OddLinkedList {

    private GoodsNode node = new GoodsNode(0,"", 0.0);

    /**
     * 往链表中添加节点
     */
    public void add(GoodsNode newNode){
        GoodsNode temp = node;
        while(true){
            if(temp.next == null){
                break;
            }
            temp = temp.next;
        }
        temp.next = newNode;
    }

    /**
     * 按照商品编号的id进行添加，从小到大的顺序
     */
    public void addById(GoodsNode newNode){
        GoodsNode temp = node;
        boolean flag = false;
        while(true){
            if(temp.next == null){
                break;
            }
            if(temp.id < newNode.id && temp.next.id > newNode.id){
                flag = true;
                break;
            }
            temp = temp.next;
        }
        if(flag){
            newNode.next = temp.next;
            temp.next = newNode;
        }
    }

    /**
     * 修改链表中的节点
     */
    public void update(GoodsNode newNode){
        GoodsNode temp = node;
        boolean flag = false;
        while(true){
            if(temp.next == null){
                break;
            }
            if(temp.id == newNode.id){
                flag = true;
                break;
            }
            temp = temp.next;
        }
        if(flag){
            temp.name = newNode.name;
            temp.price = newNode.price;
        }else {
            System.out.println("未找到要修改的节点的id");
        }
    }

    /**
     * 删除链表中的节点
     */
    public void delete(int id){
        GoodsNode temp = node;
        boolean flag = false;
        while (true){
            if(temp.next == null){
                break;
            }
            if(temp.next.id == id){
                flag = true;
                break;
            }
            temp = temp.next;
        }
        if(flag){
            temp.next = temp.next.next;
        }else {
            System.out.println("未找到要删除的节点的id");
        }
    }

    /**
     * 查看链表中的每一个节点元素
     */
    public void list(){
        if(node.next == null){
            System.out.println("链表为空");
            return;
        }
        GoodsNode temp = node.next;
        while(true){
            if(temp == null){
                break;
            }
            System.out.println(temp);
            temp = temp.next;
        }
    }

    /**
     * 统计单链表中的个数
     */
    public int getCount(){
        int count = 0;
        if(node.next == null){
            System.out.println("空链表");
            return count;
        }else {
            GoodsNode temp = node.next;
            while(temp != null){
                count++;
                temp = temp.next;
            }
        }
        return count;
    }
}
